"""
FileName：base_page.py
Description：
Author：gaojiahui
Time：2025/8/29 18:37
Website：https://gitee.com/gao-jiahui
"""
from selenium.common import TimeoutException, NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from config.config import Config


class BasePage:
    def __init__(self, driver):
        self.driver = driver
        self.timeout = Config.TIMEOUT
        self.wait = WebDriverWait(self.driver, self.timeout)

    def find_element(self, locator):
        try:
            return self.wait.until(EC.visibility_of_element_located(locator))
        except TimeoutException:
            raise NoSuchElementException(f"Element with locator {locator} not found")

    def find_elements(self, locator):
        try:
            return self.wait.until(EC.visibility_of_all_elements_located(locator))
        except TimeoutException:
            return []

    def click(self, locator):
        element = self.find_element(locator)
        element.click()

    def clear(self, locator):
        element = self.find_element(locator)
        element.clear()

    def send_keys(self, locator, text):
        element = self.find_element(locator)
        self.clear(locator)
        element.send_keys(text)
        return self

    def get_text(self, locator):
        element = self.find_element(locator)
        return element.text

    def is_element_present(self, locator):
        try:
            self.find_element(locator)
            return True
        except NoSuchElementException:
            return False

    def wait_for_element_to_disappear(self, locator):
        try:
            self.wait.until(EC.visibility_of_element_located(locator))
            return True
        except TimeoutException:
            return False

    def is_element_selected(self, locator):
        """判断元素是否选中"""
        try:
            element = self.find_element(locator)
            return element.is_selected()
        except NoSuchElementException:
            return False
